package dbutils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.apache.commons.dbutils.DbUtils;
public class DbUtilsExample {
	public static void main(String[] args) {
		String url = "jdbc:mysql://127.0.0.1:3306/test";
		String user = "root";
		String password = "123";
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection(url, user, password);
			stmt = conn.createStatement();
			stmt
					.executeUpdate("INSERT INTO test_user (USERNAME, PASSWORDHASH) values ('testUser', '123456')");
			DbUtils.closeQuietly(stmt);
			DbUtils.commitAndCloseQuietly(conn);
		} catch (SQLException ex) {
			//ex.printStackTrace();
			DbUtils.printStackTrace(ex);
			DbUtils.rollbackAndCloseQuietly(conn);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		PreparedStatement psmt = null;
		try {
			conn = DriverManager.getConnection(url, user, password);
			psmt = conn.prepareStatement("SELECT USERNAME, PASSWORDHASH FROM test_user");
			rs = psmt.executeQuery();
			while (rs.next()) {
				System.out.println(rs.getString(1) + "\t" + rs.getString(2));
			}
		} catch (SQLException ex) {
			DbUtils.printStackTrace(ex);
		} finally {
			DbUtils.closeQuietly(conn, psmt, rs);
		}
		try {
			conn = DriverManager.getConnection(url, user, password);
			stmt = conn.createStatement();
			stmt.executeUpdate("DELETE FROM user WHERE USERNAME='testUser'");
			DbUtils.closeQuietly(stmt);
		} catch (SQLException ex) {
			DbUtils.printStackTrace(ex);
		} finally {
			DbUtils.printWarnings(conn);
			DbUtils.closeQuietly(conn);
		}
	}
}
